package com.hk.commons.utils.order;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HuochaiProductBuy extends Thread {

	 

	private Logger logger = LoggerFactory.getLogger(HuochaiProductBuy.class);
	
	private Map<String, String> params;

	private String url;
	
	public HuochaiProductBuy(Map<String, String> params, String url) {
		 
		this.params = params;
		this.url = url;
	}

	public void run() {
		System.out.println("run 下单动作 开始运行" + new Timestamp(System.currentTimeMillis()));
		CloseableHttpClient httpClient = getHttpClient();

		CloseableHttpResponse httpResponse = null;
		try {
			HttpPost post = new HttpPost(this.url ); 
			// 创建参数列表
			List<NameValuePair> list = new ArrayList<NameValuePair>();

			// 添加参数
			for (String key : params.keySet()) {
				list.add(new BasicNameValuePair(key, params.get(key).toString()));
			}

			// url格式编码
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list,
					"UTF-8");
			post.setEntity(uefEntity);

			logger.info("POST 请求...." + post.getURI() + "   参数为 : "
					+ post.getEntity().toString());
			
//			// 执行请求
//			// httpResponse = httpClient.execute(post);
//
//			httpClient.execute(post);
//			try {
//				//HttpEntity entity = httpResponse.getEntity();
//				if (null != entity) {
//					logger.info("-------------------------------------------------------");
//					logger.info(EntityUtils.toString(uefEntity));
//					logger.info("-------------------------------------------------------");
//				}
//			} finally {
//				//httpResponse.close();
//			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				closeHttpClient(httpClient);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private CloseableHttpClient getHttpClient() {
		return HttpClients.createDefault();
	}

	private void closeHttpClient(CloseableHttpClient client) throws IOException {
		if (client != null) {
			client.close();
		}
	}

	 
	public Map<String, String> getParams() {
		return params;
	}

	public void setParams(Map<String, String> params) {
		this.params = params;
	}
}
